/**
 * File ControlAgentCB.java created by Pablo Díaz Fernández
 * on 12/12/2011 for the project supply-chain-simulator
 */
package org.lsk.pfc.scsim.model.behaviour;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

import org.apache.log4j.Logger;
import org.lsk.pfc.scsim.model.messages.MessageFactory;

/**
 * Cyclic behaviour executed for every control agent of the different
 * multi-agent systems of the supply chain.
 * 
 * @author Pablo Díaz Fernández
 */
public abstract class ControlAgentCB extends CyclicBehaviour {

	/**
	 * Serial version ID.
	 */
	private static final long serialVersionUID = 2707746717545365712L;

	/**
	 * Logger for the class.
	 */
	private Logger logger = null;

	/**
	 * Creates the logger for the class.
	 */
	protected abstract void createLogger();
	
	/**
	 * @see jade.core.behaviours.Behaviour#action()
	 */
	@Override
	public final void action() {
		createLogger();
		ACLMessage message = null;
		do {
			message = this.myAgent.blockingReceive();
		} while (message == null);

		if (MessageFactory.isNewTick(message)) {
			long tick = MessageFactory.extractTick(message);
			
			this.logger = Logger.getLogger(this.getClass());
			this.logger.debug("[" + myAgent.getName() + "] Tick " + tick);
			
			process(tick);
			sendEOT();
		} else if (MessageFactory.isEOE(message)) {
			this.myAgent.doDelete();
		}
	}

	/**
	 * Sends the End-Of-Tick message to the timer.
	 */
	protected final void sendEOT() {
		this.myAgent.send(MessageFactory.getEOTMsg(this.myAgent.getName()));
	}

	/**
	 * Performs operations of the agent behaviour.
	 * 
	 * @param tick
	 *            Tick indicator.
	 */
	protected abstract void process(final long tick);

	/**
     * Gets the logger.
     *
     * @return the logger
     */
    protected final Logger getLogger() {
    	return logger;
    }

	/**
     * Sets the logger.
     *
     * @param logger the logger to set
     */
    protected final void setLogger(final Logger logger) {
    	this.logger = logger;
    }
}
